package com.summer.campussct.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

@Component
public class JwtUtil {

    @Value("${jwtKey}")
    private String jwtKey;

    private SecretKey secretKey;
    @PostConstruct
    public void initKey(){
        secretKey = Keys.hmacShaKeyFor(jwtKey.getBytes());
    }

    /**
     * 生成Jwt令牌，内容为hashmap
     */
    public String generateJwtToken(Map<String, String> claims, long expire) {
        return Jwts.builder()
                .claims(claims)
                .expiration(new Date(System.currentTimeMillis() + expire * 1000))
                .signWith(secretKey, Jwts.SIG.HS256)
                .compact();
    }

    /**
     * 根据字符串生成Jwt令牌，可以为JSON字符串
     */
    public String generateJwtToken(String subject, long expireSecond) {
        return Jwts.builder()
                .subject(subject)
                .expiration(new Date(System.currentTimeMillis() + expireSecond * 1000))
                .signWith(secretKey, Jwts.SIG.HS256)
                .compact();
    }

    /**
     * 解析jwt
     * @return Claims对象：
     * <p>getSubject: 获得subject类型的内容；</p>
     * <p>toString: 获得Map中的内容(附带过期时间)</p>
     * <p>getExpired: 获得令牌过期时间</p>
     * <p>令牌过期则抛出ExpiredJwtException</p>
     */
    public Claims parseJwt(String jwt){
        return Jwts.parser()
                .verifyWith(secretKey)
                .build()
                .parseSignedClaims(jwt)
                .getPayload();
    }
}
